package com.thoughtworks.android.androsphere.service;

import android.content.Context;
import android.util.Log;
import com.thoughtworks.android.androsphere.R;
import com.thoughtworks.android.androsphere.framework.UserEmailFetcher;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;

public class BroadcastServiceClient implements ServiceClient {
    private static final String TAG = BroadcastServiceClient.class.getName();

    Context context;
    String message;

    public BroadcastServiceClient (Context context, String message) {
        this.context = context;
        this.message = message;
    }

    public void execute() {
        Log.d(TAG, "Inside BroadcastServiceClient execute method");
        final String userEmail = UserEmailFetcher.getEmail(context);
        final String requestString = "device:" + userEmail + ";data:" + message + ";";

        final String broadcastServiceUrl = context.getResources().getString(R.string.app_server_base_url) + "broadcast";
        Log.d(TAG, "********broadcastServiceUrl " + broadcastServiceUrl);
                
        postData(broadcastServiceUrl, requestString);
    }

    private void postData(final String url, final String requestString) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(url);
        try {
            postRequest.setHeader("Content-Type","text/plain");
            postRequest.setEntity(new ByteArrayEntity(requestString.getBytes()));
            HttpResponse response = httpclient.execute(postRequest);
            Log.d(TAG, "Successful BroadcastService Call");
        } catch (IOException e) {
            Log.d(TAG,"exception");
            Log.d(TAG,e.getMessage());
        }
        finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
}
